package com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.service.impl;

import cn.hutool.core.util.IdUtil;
import com.css.fxfzxczh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzxczh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.entity.LosRepManage;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.entity.ReportPublicField;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.queryParams.QueryParams;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.repository.LosRepEscalationRepository;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.repository.ReportPublicFieldRepository;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.service.LosRepEscalationService;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.strategy.StrategyFactory;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.strategy.StrategyService;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.vo.LosRepManageVo;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.util.CreateGson;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.util.RemoteTransfer;
import com.css.fxfzxczh.util.UUIDGenerator;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import com.css.fxfzxczh.zcpt.sys.service.impl.SUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import static com.css.fxfzxczh.util.PoiExcelUtil.getWorkBook;

@Slf4j
@Service
public class LosRepEscalationServiceImpl implements LosRepEscalationService {

    @Resource
    LosRepEscalationRepository losRepEscalationRepository;

    @Resource
    StrategyFactory strategyFactory;//策略工厂

    @Autowired
    SUserServiceImpl sUserServiceImpl;

    @Resource
    ReportPublicFieldRepository reportPublicFieldRepository;

    @Resource
    private AttachmentInfoService attachmentInfoService; // 附件
    @Autowired
    private SUserService sUserService;
    @Autowired
    private EarEveManageService earEveManageService;

    @Value("${image.localDir}")
    private String localDir;

    @Override
    public Map<String, Object> getPage(QueryParams queParams, int curPage, int pageSize) {
        Map<String, Object> page = losRepEscalationRepository.getPage(queParams, curPage, pageSize);
        return page;
    }

    @Override
    public void check(List<String> idList, String checkStatus, String checkOpinion) {
        losRepEscalationRepository.check(idList,checkStatus,checkOpinion);
        //将审核成功的批量修改为可见
        reportPublicFieldRepository.update(idList);
    }

    @Override
    public void submit(String ids) {
        String[] split = ids.split(",");
        for(String id:split){
            losRepEscalationRepository.submit(id);
        }
    }

    @Override
    public LosRepManageVo findById(String id) {
        LosRepManage losRepManage=losRepEscalationRepository.findById(id);
        LosRepManageVo losRepManageVo=new LosRepManageVo();
        //AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(losRepManage.getAttachmentId());
        if(PlatformObjectUtils.isNotEmpty(losRepManage.getAttachmentId())){
            losRepManageVo.setAttachment(attachmentInfoService.getAttach(losRepManage.getAttachmentId()));
        }
        BeanUtils.copyProperties(losRepManage, losRepManageVo);
        return losRepManageVo;
    }

    @Transactional
    @Override
    public String reportImport(MultipartFile file, String category,String xsemId,String isHavaLossValue,String attachmentId) {

        StrategyService service = strategyFactory.getService(category);
        String userId = PlatformSessionContext.getUserID();
/*        userId="80cd530287e54c6788925adf2dfc9da1";*/
        //根据文件类型名称,地震事件id,用户id获取文件主表id
        EarEveManage currentEvent = earEveManageService.findById(xsemId);//获取当前地震事件
        String previousXlrmId=losRepEscalationRepository.isHaveSameTypeReport(category,xsemId,userId);
        if(!PlatformObjectUtils.isEmpty(previousXlrmId)){
            losRepEscalationRepository.deleteById(previousXlrmId);
        }
        try {
            String sUser = sUserServiceImpl.getSUser(userId);
            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            LosRepManage losRepManage=new LosRepManage();
            String id = UUIDGenerator.getUUID();
            losRepManage.setId(id);
            //地震事件id
            losRepManage.setXsemId(xsemId);
            losRepManage.setReportType(category);
            //设置审核状态为未提交
            losRepManage.setCheckStatus("0");
            losRepManage.setAttachmentId(attachmentId);
            losRepManage.setCreateUser(userId);
            losRepManage.setCreateTime(new Date());
            losRepManage.setCreateUserName(userInfo.getUserName());
            losRepManage.setIsHavaLossValue(isHavaLossValue);
            losRepEscalationRepository.save(losRepManage);
            Workbook workbook = getWorkBook(file);
            //导入数据
            if("是".equals(isHavaLossValue)){
                if(workbook != null){
                    ReportPublicField reportPublicField =new ReportPublicField();
                    //地震事件id
                    reportPublicField.setXsemId(xsemId);
                    //报表主表id
                    reportPublicField.setXlrmId(id);
                    reportPublicField.setCreateUser(userId);
                    //报表类型
                    reportPublicField.setReportType(category);
                    service.reportImport(workbook,id,previousXlrmId,reportPublicField);
                }
            }
            transReportMsgToCpxx(file,currentEvent.getEventName(),currentEvent.getEventTime());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }

        return "导入成功";
    }

    private void transReportMsgToCpxx(MultipartFile file,String keyword,String shockTime) {
        String fileName = file.getOriginalFilename();
        String userId = PlatformSessionContext.getUserID();
        String userJson = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        //获取创建人单位
        String orgName = sUser.getOrgName();
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("cpxxRestUrl") + "/infAchievement/dockingOtherSystem";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization", IdUtil.simpleUUID());

        Map<String, String> valueMap = new HashMap<>();
        valueMap.put("sign", "2");
        valueMap.put("dataOrigin", "6");
        valueMap.put("publishingUnit", orgName);
        valueMap.put("createUser", userId);
        valueMap.put("achievementName", fileName);
        valueMap.put("keyword", keyword);
        valueMap.put("shockTime", shockTime);
        Map<String, MultipartFile> fileParams = new HashMap<>();
        fileParams.put("file", file);
        String res = RemoteTransfer.uploadFile(url, fileParams, valueMap, null);
    }
}
